﻿Imports System
Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Imports System.Security.Cryptography

Public Class Form1

    '****************************
    Dim port As Int32 = 33012
    '****************************

    Dim clientSocket As New System.Net.Sockets.TcpClient()
    Dim serverStream As NetworkStream
    Dim counter As Integer = 1

    Private Sub Send_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles Button1.Click

        Try

            If clientSocket.Connected Then

                Dim SendingMessage As String = TextBox1.Text
                Dim SendBuffer As Byte()

                SendBuffer = ToBytes(SendingMessage)

                serverStream.Write(SendBuffer, 0, SendBuffer.Length)
                serverStream.Flush()

                msg("Sent: " & SendingMessage)

                Dim readText As String = ""
                Dim ReadBuffer() As Byte
                Dim sizeBytes(3) As Byte

                serverStream.Read(sizeBytes, 0, 4)

                Dim sizeInt As Integer = Integer.Parse(System.Text.Encoding.ASCII.GetString(sizeBytes))

                ReadBuffer = New Byte(sizeInt - 1) {}

                serverStream.Read(ReadBuffer, 0, sizeInt)

                readText = ToText(ReadBuffer)

                msg("Data from Server : " + readText)



                If clientSocket.Connected = False Then
                    msg("Server Disconnected")
                    Me.Name = "Socket Client"
                    CloseConn()
                    Exit Sub
                End If

            Else
                msg("Server Disconnected")
                Me.Name = "Socket Client"
                CloseConn()
                Exit Sub
            End If


        Catch ex As Exception
            msg("Error: " & ex.Message)
            CloseConn()
            Me.Name = "Socket Client"
        End Try


    End Sub

    Private Sub Form1_Load(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles MyBase.Load
        TextBox2.Text = My.Settings.Server
        msg("Client Started")
    End Sub

    Public Sub CloseConn()
        Try
            serverStream.Close()
            clientSocket.Close()
            clientSocket = New Net.Sockets.TcpClient()
        Catch ex As Exception

        End Try
        counter = 1
    End Sub


    Private Sub Connect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click

        If clientSocket.Connected = False Then 'Connect
            Try
                clientSocket = New System.Net.Sockets.TcpClient()
                clientSocket.Connect(TextBox2.Text, port)
                serverStream = clientSocket.GetStream()
                Me.Text = "Socket Client - Connected"
                msg("Connected!")
            Catch ex As Exception
                msg("Could not connect")
            End Try

        Else ' Disconnect
            Try
                serverStream.Close()
                clientSocket.Close()
            Catch ex As Exception
            End Try

            clientSocket = New Net.Sockets.TcpClient()
            Me.Name = "Socket Client"
            msg("Disconnected!")

        End If



    End Sub


    Private Sub Form1_FormClosing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
        If clientSocket.Connected Then
            clientSocket.Close()
            clientSocket = New Net.Sockets.TcpClient()
            Me.Name = "Socket Client"
            msg("Disconnected to server")
        End If
        My.Settings.Server = TextBox2.Text
    End Sub

    Private Sub ToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem1.Click
        TextBox3.Text = ""
    End Sub


    Private Function ToBytes(ByVal textToConvert As String) As Byte()

        Dim TextArr As Byte() = System.Text.Encoding.UTF8.GetBytes(textToConvert)

        Dim textSize As Integer = TextArr.Length
        Dim textString As String = textSize.ToString().PadLeft(4, "0")

        Dim ByteArr As Byte() = New Byte(textSize + 3) {}

        System.Text.Encoding.ASCII.GetBytes(textString, 0, textString.Length, ByteArr, 0)

        System.Buffer.BlockCopy(TextArr, 0, ByteArr, textString.Length, textSize)
        Return ByteArr
    End Function


    Private Function ToText(ByVal bytesToDecode As Byte()) As String

        Return System.Text.Encoding.UTF8.GetString(bytesToDecode)

    End Function


    Sub msg(ByVal mesg As String)
        TextBox3.AppendText(mesg + Environment.NewLine)
    End Sub

End Class
